package com.dyh.quickdemo.dasync;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.PostConstruct;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class AsynRunListener {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private ThreadPoolExecutor threadPoolExecutor;//不用这个还是原来的线程

    @Autowired
    AsyncHandlerCoreService coreService;

    @PostConstruct
    public void pc() {
        //初始化备注换货线程池,线程创建工厂和拒绝策略用默认即可
        ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(3000);
        this.threadPoolExecutor = new ThreadPoolExecutor(10, 15, 180, TimeUnit.SECONDS, queue);
        this.threadPoolExecutor.allowCoreThreadTimeOut(true);
    }
    //使用默认处理阶段，在事务成功提交之后便能监听到
    //@TransactionalEventListener
    @EventListener//这个不用等事务
    public void runImmediately(AsyncEvent event){
        logger.info("{} event {}",Thread.currentThread().getName(),JSON.toJSONString(event));

//        threadPoolExecutor.execute(()->
//                        coreService.run(event.getAsyncEventContext())
//                );
    }
}
